package com.fishery.base.controller;


import com.fishery.base.entity.Base;
import com.fishery.base.entity.vo.CreateBaseVo;
import com.fishery.base.service.BaseService;
import com.fishery.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 基地前端控制器
 * </p>
 *
 * @author Ghost
 * @since 2021-01-15
 */
@RestController
@RequestMapping("/base")
@Api(tags = "基地相关信息模块")
@CrossOrigin
public class BaseController {

	@Autowired
	private BaseService baseService;


	@PostMapping("/create")
	@ApiOperation("创建基地")
	public Result createBase(@RequestBody @ApiParam(required = true, value = "base对象") CreateBaseVo vo) {
		if (vo == null
				|| vo.getTypes() == null
				|| vo.getTypes().isEmpty()
				|| StringUtils.isEmpty(vo.getCreator())
				|| StringUtils.isEmpty(vo.getName())) {
			return Result.error("创建失败");
		}
		// 保存创建基地信息
		String baseId = baseService.establishBase(vo);
		return baseId == null ? Result.error("创建失败") : Result.success().data(baseId);
	}


	@GetMapping("/{baseId}")
	@ApiOperation("通过基地Id获取基地信息")
	public Result getBaseInfo(@PathVariable(name = "baseId", required = true)
							  @ApiParam(required = true, value = "baseId") String baseId) {
		// 判断BaseId是否为空，防止用户非法操作
		if (StringUtils.isEmpty(baseId)) {
			return Result.error();
		}
		// 从数据库中查询该baseId的基地是否存在
		Base base = baseService.getById(baseId);
		return base == null ? Result.error() : Result.success ().data(base);
	}


	@GetMapping
	@ApiOperation("获取所有基地的信息")
	public Result getBaseInfo() {
		List<Base> bases = baseService.list(null);
		return Result.success().data(bases);
	}


	@PutMapping("/update")
	@ApiOperation("修改基地信息")
	public Result updateBaseInfo(@RequestBody @ApiParam(required = true, value = "base对象") Base base) {
		// 判断base或baseId是否为空，防止非法操作
		if (base == null || StringUtils.isEmpty(base.getId())) {
			return Result.error();
		}
		// 修改数据库中的信息
		return baseService.updateById(base) ? Result.success("修改成功") : Result.error("修改失败");
	}

}

